﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Socium.Domain.Collections {
	public static class CollectionExtensions {
		public static TTarget[] MapToArray<TSource, TTarget>(this ICollection<TSource> collection, Func<TSource, TTarget> mapper) {
			var count = collection.Count;
			var result = new TTarget[count];

			var index = 0;
			foreach (var item in collection) {
				result[index] = mapper(item);
				index++;
			}

			return result;
		}

		public static CollectionResult<TTarget> Map<TSource, TTarget>(this ICollection<TSource> collection, Func<TSource, TTarget> mapper) {
			var result = new List<TTarget>(collection.Count);
			result.AddRange(collection.Select(mapper));

			return new CollectionResult<TTarget>(result);
		}

		public static CollectionResult<T> Filter<T>(this ICollection<T> collection, Func<T, bool> predicate) {
			var result = new List<T>(collection.Count);
			result.AddRange(collection.Where(predicate));

			return new CollectionResult<T>(result);
		} 

		public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items) {
			items.Iterate(collection.Add);
		}

		public static int Count<T>(ICollection<T> collection) {
			return collection.Count;
		}

		public static T[] ToArray<T>(this ICollection<T> collection) {
			var result = new T[collection.Count];
			collection.CopyTo(result, 0);

			return result;
		}
	}
}
